<template>
  <div>
    <div class="tags">
      <ul class="current">
        <li
          :class="{ selected: selectedTag.indexOf(i) >= 0 }"
          v-for="i in dataSource"
          :key="i.id"
          @click="toggle(i)"
        >
          {{ i.name }}
        </li>
      </ul>
      <div class="new">
        <button @click="addTag">新增标签</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";
import tagListModel from "@/models/tagListModel";
type Tag = {
  id: string;
  name: string;
};
@Component
export default class Tags extends Vue {
  @Prop(Array) dataSource!: Tag[];
  selectedTag: Tag[] = [];
  toggle(i: Tag) {
    const index = this.selectedTag.indexOf(i);
    if (index >= 0) {
      this.selectedTag.splice(index, 1);
    } else {
      this.selectedTag.push(i);
    }
    this.$emit("update:value", this.selectedTag);
  }
  addTag() {
    console.log('我是tag啊 别出发我');
    
    const name = window.prompt("请输入标签名");
    if (name) {
      const msg = tagListModel.add(name);
      if (msg === "duplicated") {
        alert("标签名已重复");
      } else if (msg === "success") {
        alert("标签名创建成功");
      }
      this.$emit("update:dataSource", [...this.dataSource, { id: name, name }]);
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/helper.scss";
.tags {
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  flex-grow: 1;
  font-size: 14px;
  padding: 16px;
  height: 200px;

  > .current {
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    // justify-content: flex-end;
    > li {
      background: #d9d9d9;
      $h: 24px;
      height: $h;
      line-height: $h;
      border-radius: $h/2;
      padding: 0 16px;
      margin-bottom: 4px;
      margin-right: 12px;
      &.selected {
        background-color: #8f8f8f;
        color: white;
      }
    }
  }
  > .new {
    padding: 16px 0;
    button {
      background: transparent;
      border: none;
      color: #999;
      border-bottom: 1px solid;
      padding: 0 3px;
    }
  }
}
</style>
